import { MutableRefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import Region from './Region';
import { List, Popup, SearchBar, Selector, Radio, Space, Dialog, Popover, Toast } from 'antd-mobile';
import {
  deleteSearchHistoryByModule,
  deleteSingleSearchHistory,
  fetchSearchKeyHotWord,
  getSearchHistory,
} from '../../../designer/service';
import { SearchOutline } from 'antd-mobile-icons';
import { InbizIcon } from '@inbiz/utils';
import { TabsConfigState } from '../../../store/searchPropsContext';
import { ecmSearchTypeField } from '../../../store/hooks/useJumpResult';
import { ISearchWapProps } from '..';
import { TextWidget, getMessage } from '@inbiz/react';
import useConfigApi from '../../../../SearchResultEngine/preview/common/useConfigApi';
import { routerPrefix } from 'InbizConfig';
import { InputRef } from 'antd-mobile/es/components/input';
// import AdvancedSearch from './AdvancedSearch/index'
interface IContentProps {
  title: {
    status: boolean;
    value: string;
  };
  indexRange: boolean;
  hotKeywordsNumber: number;
  tabsConfig: TabsConfigState[];
  searchResult: { [key: string]: any };
  emit: (type: string, searchResultComponent: any, params: any) => void;
  setVisible: (visible: boolean) => void;
  setSearchValue: (value: string) => void;
  hotKeywordsSwitch: boolean;
  configEvents: MutableRefObject<ISearchWapProps['callBackEvents']>;
  searchResultPageType: ISearchWapProps['searchResultPageType'];
  inbiz: any;
  placeholder: string;
  icon: {
    color: string;
    type: string;
  };
  historySearch: boolean;
  IsSynonymSearch: boolean;
  rangeType?: 'pull' | 'popup'
  searchValue?: string,
  searchType: 'accurateSearch' | 'vagueSearch'
  tagConfig: TabsConfigState
  setSearchType: Function,
  setTagConfig: Function,
  clearStorage: Function
}
interface IDocumentRadioData {
  data: { label: string; value: string }[];
  value: string | number;
  change: (value: string | number) => void;
}

const fileTypeOptions = [
  {
    label: 'SearchEngine.currentFolder',
    value: 'currentFolder',
  },
  {
    label: 'SearchEngine.fullLibrary',
    value: 'all',
  },
];
const searchTypeOptions = [
  {
    label: 'SearchEngine.fuzzySearch',
    value: 'vagueSearch',
  },
  {
    label: 'SearchEngine.preciseSearch',
    value: 'accurateSearch',
  },
];
const Content = (props: IContentProps) => {
  const {
    rangeType = 'popup',
    indexRange,
    tabsConfig,
    searchResult,
    hotKeywordsNumber,
    emit,
    setVisible,
    setSearchValue,
    hotKeywordsSwitch,
    searchResultPageType,
    configEvents,
    icon,
    placeholder,
    historySearch,
    IsSynonymSearch,
    searchValue,
    tagConfig, setTagConfig,
    searchType, setSearchType,
    clearStorage
  } = props;
  const configEventsApi = useConfigApi(configEvents);
  const searchBarRef = useRef<InputRef>(null);
  const [historyList, $historyList] = useState<string[]>([]); // 历史记录
  const [hotWord, $HotWord] = useState<string[]>([]); // 热门搜索
  const [showPopup, setShowPopup] = useState<boolean>(false); // 是否显示弹出层
  const [documentType, setDocumentType] = useState<string[]>(() => {
    // 文档类型
    const list = tabsConfig
      .find((item) => item.isDMS || item.isFile || item.isFolder)
      ?.searchType?.map((item) => item.value.toString());
    if (list?.length) {
      if (list.length === 1 && list[0] === '4') {
        return list;
      } else {
        return list.filter((item) => item != '4');
      }
    }
    return [];
  });
  const [folderType, setFolderType] = useState<string | number>('all'); // 文档类型为文件夹时，记录是当前文件夹还是全库
  //const [searchType, setSearchType] = useState<string | number>(() => !storage?.isFuzzySearch ? 'accurateSearch' : 'vagueSearch'); // 查询类型，模糊查询或者精确查询
  const [keyWord, setKeyWord] = useState<string>(''); // 搜索关键词
  // const [tagConfig, setTagConfig] = useState<TabsConfigState>(() => {
  //   if (storage?.ModuleName) {
  //     return tabsConfig.find(item => item.guid === storage?.ModuleName) || tabsConfig[0]
  //   } else {
  //     return tabsConfig[0]
  //   }
  // }); // 当前选择的标签配置
  useEffect(() => {
    setKeyWord(searchValue || '')
  }, [searchValue]);

  const fileType = useMemo(() => {
    if (documentType.some((type) => type === '4')) {
      return 'folder';
    }
    return 'file';
  }, [documentType]);
  // 初始化数据
  const initData = async () => {
    const historyParams = {
      Size: 8,
    };
    let indexLibraryName = '';
    if (!tagConfig?.isAll && !tagConfig?.isDMS) {
      indexLibraryName = tagConfig?.indexLibraries?.length
        ? tagConfig.indexLibraries[0]?.IndexName
        : '';
    }
    if (tagConfig?.isDMS) {
      indexLibraryName = fileType;
    }

    const historyData = await configEventsApi({
      request: getSearchHistory,
      params: historyParams,
      keys: ['onHistoryParams', 'onHistory', 'onHistoryData'],
    });

    const hotWordData = await configEventsApi({
      request: fetchSearchKeyHotWord,
      params: {
        Size: hotKeywordsNumber,
      },
      keys: ['onHotWordParams', 'onHotWord', 'onHotWordData'],
    });
    if (hotWordData.Code == 0) {
      $HotWord(hotWordData.Data);
    }
    if (historyData.Code == 0) {
      $historyList(historyData.Data);
    }
  };
  // 渲染搜索的Icon
  const renderIcon = useMemo(() => {
    if (indexRange) {
      return (
        <div>
          {
            rangeType === 'pull' ?
              <Popover.Menu
                className="searchEngine-indexRangePopover"
                actions={tabsConfig.map(item => {
                  return {
                    key: item.guid,
                    text: <span style={{ color: tagConfig.title === item.title ? 'var(--ant-primary-color)' : 'var(--inbiz-color-heading)' }}>{getMessage(item.title)}</span>,
                    onClick: () => {
                      setTagConfig(item);
                    }
                  }
                })}
                placement='bottom'
                trigger='click'
              >
                <span className="inbiz-search-all-btn">
                  {getMessage(tagConfig.title) || getMessage('SearchEngine.whole')}
                </span>
              </Popover.Menu> :
              <span className="inbiz-search-all-btn" onClick={() => setShowPopup(true)}>
                {getMessage(tagConfig.title) || getMessage('SearchEngine.whole')}
              </span>
          }

          <span className="inbiz-region-cut-line search-icon-cut-line"></span>
          {icon?.type ? <InbizIcon type={icon?.type} style={{ color: icon.color }} /> : null}
        </div>
      );
    }
    return icon?.type ? <InbizIcon type={icon?.type} style={{ color: icon.color }} /> : null;
  }, [indexRange, tagConfig, icon, rangeType, tagConfig.title]);
  // 渲染弹出层内容
  const renderPopupContent = useMemo(() => {
    return (
      <div>
        <div className="inbiz-popop-header">
          <span className="inbiz-popop-header-title">
            <TextWidget>SearchEngine.selectSearchScope</TextWidget>
          </span>
          <span className="inbiz-popop-header-close" onClick={() => setShowPopup(false)}>
            <InbizIcon type="icon-ic-close-bold" />
          </span>
        </div>
        <div className="inbiz-popop-list">
          <List>
            {tabsConfig.map((config) => {
              return (
                <List.Item key={config.guid}>
                  <div
                    className={`inbiz-popop-item ${tagConfig.title === config.title ? 'inbiz-popop-item-selected' : ''
                      }`}
                    onClick={() => {
                      setTagConfig(config);
                      setShowPopup(false);
                    }}
                  >
                    <span>{getMessage(config.title)}</span>
                    {
                      tagConfig.title === config.title && <div className='searchEngine-radio-icon'></div>
                    }
                  </div>
                </List.Item>
              );
            })}
          </List>
        </div>
      </div>
    );
  }, [tagConfig]);
  /**
   * 选择文档类型时，判断当前选择的类型，文件夹只能单选，其余几个可以多选
   * @param value 当前选择的类型
  const selectDocumentType = (value: string[]) => {
    if (value.length) {
      if (value[value.length - 1] === '4') {
        setDocumentType(['4']);
      } else if (value.some((item) => item === '4')) {
        value = value.filter((item) => item !== '4');
        setDocumentType(value);
      } else {
        setDocumentType(value);
      }
    }
  };
  */
  // 渲染单选按钮组
  const renderDocumentRadio = useCallback(
    (params: IDocumentRadioData) => {
      const { data, value, change } = params;
      return (
        <div className="inbiz-search-document-config-radio">
          <Radio.Group value={value} onChange={(value) => change(value)}>
            <Space style={{ '--gap': '56px' }}>
              {data.map((option) => {
                return (
                  <Radio
                    style={{
                      '--icon-size': '18px',
                      '--font-size': '14px',
                      '--gap': '6px',
                    }}
                    value={option.value}
                    key={option.value}
                  >
                    <TextWidget>{option.label}</TextWidget>
                  </Radio>
                );
              })}
            </Space>
          </Radio.Group>
        </div>
      );
    },
    [folderType, searchType],
  );
  // 文档类型为文档时，渲染相关配置项
  const renderDocumentConfig = useMemo(() => {
    // const type =
    //   tagConfig?.searchType?.map((item) => {
    //     return {
    //       ...item,
    //       value: item.value.toString(),
    //       label: getMessage(item.label),
    //     };
    //   }) || [];
    if (tagConfig.isDMS || tagConfig.isFile || tagConfig.isFolder) {
      return (
        <div className="dms-search-box">
          {/* <p className="dms-search-condition">
            {' '}
            <TextWidget>SearchEngine.searchCriteria</TextWidget>
          </p>
          {tagConfig.searchType?.length && (
            <div className="inbiz-search-document-config">
              <Selector
                value={documentType}
                showCheckMark={false}
                multiple={true}
                onChange={selectDocumentType}
                options={type}
              />
            </div>
          )}
          {renderDocumentRadio({
            data: fileTypeOptions,
            value: folderType,
            change: setFolderType,
          })} */}
          {tagConfig.searchMode &&
            renderDocumentRadio({
              data: searchTypeOptions,
              value: searchType,
              change: setSearchType,
            })}
        </div>
      );
    }
    return null;
  }, [tagConfig, documentType, folderType, searchType]);
  /**
   * 删除单个历史记录
   * @param tagName 标签名称
   */
  const deleteTag = async (tagName: string, index: number) => {
    try {
      $historyList((list) => list.filter((_, itemIndex) => itemIndex != index));
      const res = await deleteSingleSearchHistory(tagName);
      if (!res) {
        return;
      }
    } catch (error) { }
  };
  // 删除全部历史记录
  const deleteAllTag = async () => {
    Dialog.confirm({
      content: getMessage('SearchEngine.deleteHistory'),
      onConfirm: () => {
        $historyList([]);
        deleteSearchHistoryByModule(tagConfig.guid);
      },
      cancelText: getMessage('SearchEngine.cancel'),
      confirmText: getMessage('SearchEngine.confirm'),
    });
  };
  /**
   * 单击某个tag
   * @param tagName 标签名称
   */
  const clickTag = (tagName: string) => {
    searchClick(tagName);
  };
  // 搜索事件
  const searchClick = async (tagName?: string) => {
    const { isAll, isDMS, isFile, isFolder, guid, indexLibraries, selectFolderID } = tagConfig;
    const SearchFields = [];
    if ((isDMS || isFile || isFolder) && documentType) {
      SearchFields.push(
        ...documentType.map((item) => ({ IndexFieldName: ecmSearchTypeField[item] })),
      );
    }
    const isAdvanced = false;
    const value = tagName || keyWord;
    if (!value) {
      return Toast.show(getMessage('SearchEngine.pleaseEnterKeywords'))
    }
    let SearchWhere = '';
    // dms普通搜索时， 或者为高级搜索时添加
    if (isAdvanced) {
      SearchWhere += value?.data?.SearchWhere || '';
    } else {
      if (isDMS || isFile || isFolder) {
        const key = documentType.includes('4') ? 'folder' : 'file';
        let folderid =
          folderType == 'currentFolder'
            ? selectFolderID?.[0]?.parentfolderid == 2
              ? props.inbiz.userInfo.topPersonalFolderId
              : selectFolderID?.[0].folderid
            : '';
        if (folderid) {
          SearchWhere += `${key}path:(${folderid})`;
        }
      }
    }
    const params = {
      IndexName: isAll
        ? ['_all_']
        : isDMS
          ? ['_document_']
          : indexLibraries?.map((item) => item.IndexName),
      //documentType: isDMS || isFile || isFolder ? isAdvanced ? value?.dmsType : documentType?.includes('4') ? 'folder' : 'file' : undefined,
      isFuzzySearch: searchType === 'vagueSearch',
      SearchFields: searchType === 'vagueSearch' ? SearchFields : [],
      FuzzyFields: searchType !== 'vagueSearch' ? SearchFields : [],
      SearchWhere,
      isAdvanced,
      KeyWord: !isAdvanced ? value : '',
      ModuleName: guid,
      IsSynonymSearch,
    };
    //@ts-ignore
    const data = (await props.configEvents.current.onBeforeSearch?.(params)) ?? params;
    window.localStorage.setItem('_searchEngineStatus', JSON.stringify(data));
    if (searchResult?.searchResultType == 'page' && searchResult.searchResultPage) {
      const pageId = searchResult.searchResultPage.split(',')[0];
      const path = `${location.pathname}${location.search}#${routerPrefix}${searchResult?.searchResultPage.split(',')[0]
        }`;
      // 移动化 不支持新窗口打开，有兼容性问题
      if (location.hash == `#${routerPrefix}${searchResult?.searchResultPage.split(',')[0]}`) {
        // 绑定类型为页面时, 没有搜索结果组件的id, 所以查找整个页面的搜索结果组件来获取搜索结果组件的id
        const resultComponentId = pageId.split('/')[1]
        if (window.inbizGlobal(resultComponentId).page) {
          const allPages = window.inbizGlobal(resultComponentId).page.getFields()
          const searchResultPage = allPages.find(item => item && item.componentType == 'SearchResultEngine') || {}
          const searchResultId = searchResultPage?.componentProps.controlId
          if (searchResultId) {
            props.emit?.('onSearch', searchResultId, data);
            setVisible(false);
          }
        }

      } else {
        window.location.href = path;
        setVisible(false);
      }
    } else {
      emit?.('onSearch', searchResult?.searchResultComponent, data);
      setVisible(false);
    }
    setSearchValue(value || '');
  };
  useEffect(() => {
    searchBarRef.current?.focus();
    const closePortal = () => setVisible(false)
    window.addEventListener('popstate', closePortal)
    return () => {
      window.removeEventListener('popstate', closePortal)
    }
  }, []);
  useEffect(() => {
    initData();
  }, [tagConfig, fileType]);

  return (
    <div className="inbiz-search-engine-content">
      <div className="search-main">
        <div className="content-search">
          <SearchBar
            ref={searchBarRef}
            placeholder={getMessage(placeholder)}
            className="custom-search-bar"
            icon={
              tabsConfig?.length > 1 ? (
                renderIcon
              ) : icon?.type ? (
                <InbizIcon type={icon?.type} style={{ color: icon.color }} />
              ) : null
            }
            value={keyWord}
            onChange={(val) => setKeyWord(val)}
            onSearch={() => searchClick()}
            clearable
            onClear={() => {
              clearStorage()
              configEvents.current?.onCustomClear?.()
            }}
          />
          <span className="content-search-btn" onClick={() => setVisible(false)}>
            {/* <span className="content-search-btn" onClick={() => searchClick()}> */}
            <TextWidget>SearchEngine.cancel</TextWidget>
          </span>
        </div>
        {renderDocumentConfig}
        {!!historyList?.length && historySearch && (
          <Region
            title={getMessage('SearchEngine.history')}
            showicon={true}
            tagList={historyList}
            deleteTag={deleteTag}
            deleteAllTag={deleteAllTag}
            clickTag={clickTag}
            indexLibraryName={tagConfig?.indexLibraryName}
          />
        )}
        {hotKeywordsSwitch && (
          <Region
            title={getMessage('SearchEngine.HotKeywords')}
            clickTag={clickTag}
            tagList={hotWord}
            indexLibraryName={tagConfig?.indexLibraryName}
          />
        )}

        {/* <Divider className='advanced-entry'>高级搜索</Divider> */}
      </div>
      <Popup
        visible={showPopup}
        onMaskClick={() => {
          setShowPopup(false);
        }}
        bodyClassName="searchEngine-popup"
      >
        {renderPopupContent}
      </Popup>
    </div>
  );
};

export default Content;
